from django.db import transaction
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.views import APIView
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import SystemLog, Upload, Option
from apps.article.models import Article
from .serializers import AdornProcessSerializer
from .models import AdornProcess
from .filters import AdornProcessFilter


class AdornProcessViewSet(CustomModelViewSet):
    '''后台article CRUD操作'''
    permission_classes = [permissions.IsAdminUser]
    queryset = AdornProcess.objects.filter()
    serializer_class = AdornProcessSerializer

    def filter_queryset(self, queryset):
        f = AdornProcessFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    @action(methods=['post'], detail=True)
    def relate_article(self, request, pk):
        try:
            new_relate_ids = request.data
            adorn_process = AdornProcess.get_instance_by_id(pk)
            with transaction.atomic():
                adorn_process.related_articles.clear()
                adorn_process.related_articles.add(*Article.objects.filter(id__in=new_relate_ids))
            return response_ok()
        except Exception as e:
            return response_error(str(e))
